package org.yh.demo.algorithm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Solution0001 {

    private Map<Integer,Node> map = new HashMap();

    private Node head = null;

    private Node tail = null;

    private int cap;

    class Node{
        int key;
        int value;
        Node pre;
        Node next;
        public Node(int key, int value){
            this.key = key;
            this.value = value;
        }
    }

    /**
     * lru design
     * @param operators int整型二维数组 the ops
     * @param k int整型 the k
     * @return int整型一维数组
     */
    public int[] LRU (int[][] operators, int k) {
        // write code here
        cap = k;
        int len = (int) Arrays.stream(operators).filter(x -> x[0] == 2).count();
        int[] res = new int[len];
        int j = 0;
        for(int[] operator:operators){
            int type = operator[0];
            if(type == 1){
                set(operator[1],operator[2]);
            }else if(type == 2){
                Node node = get(operator[1]);
                res[j++] = (node==null)?-1:node.value;
            }
        }
        return res;
    }

    private void set(int k, int v){
        Node node = map.get(k);
        if(node == head){
            node.value = v;
            return;
        }

        if(node!=null){
            node.pre.next = node.next;
            if(tail == node){
                tail = node.pre;
            }else{
                node.next.pre = node.pre;
            }
            map.remove(k);
            node.next = null;
            node.pre = null;
        }
        node = new Node(k,v);
        if(head != null){
            node.next = head;
            head.pre = node;
        }
        head = node;
        map.put(k, node);
        if(tail == null){
            tail = node;
        }
        if(map.size() > cap){
            map.remove(tail.key);
            tail = tail.pre;
            tail.next.pre = null;
            tail.next = null;
        }
        return;
    }

    private Node get(int k){
        Node node = map.get(k);
        if(node!=null){
            set(k, node.value);
            return node;
        }else{
            return null;
        }
    }


    public static void main(String[] args) {
        int[] aa = new int[4];
//        System.out.println(aa.length);
        char a='(';
        char b=')';
        System.out.println(((int)'{') +":"+((int)'}'));
        System.out.println(b-a);
    }

}
